package com.onenine.chat.rongcloud;

import android.util.ArrayMap;

import com.onenine.app.db.DataManager;
import com.onenine.app.request.RUserRequest;
import com.onenine.app.response.RUserResponse;
import com.onenine.app.utils.UrlConfig;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.chat.commons.IUser;
import com.onenine.chat.model.LUser;
import com.onenine.common.util.Logger;
import com.onenine.common.util.StringUtils;

import org.litepal.crud.DataSupport;
import org.litepal.crud.callback.FindCallback;
import org.litepal.crud.callback.FindMultiCallback;
import org.litepal.crud.callback.SaveCallback;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户资料管理
 * 创建人： fly
 */

public class UserCacheMgr {

    private static UserCacheMgr userMgr;
    private ArrayMap<String, LUser> userMap;

    public interface OnUserCallback {
        void callback(LUser user);
    }

    public interface OnUsersCallback {
        void callback(List<LUser> userList);
    }

    private UserCacheMgr() {
        userMap = new ArrayMap<>();
    }

    public static UserCacheMgr getInstance() {
        if (userMgr == null) {
            userMgr = new UserCacheMgr();
        }
        return userMgr;
    }

    private void getUserFromDB(final String userId, final OnUserCallback callback) {
        DataSupport.where("userId=?", userId).findLastAsync(LUser.class).listen(new FindCallback() {
            @Override
            public void onFinish(Object t) {
                if (t == null) {
                    getUserFromNetwork(userId, callback);
                } else {
                    userMap.put(userId, (LUser) t);
                    callback.callback((LUser) t);
                }
            }
        });
    }

    public void getUsersFromDB(final OnUsersCallback callback, String... userIds) {
        DataSupport.where(String.format("userId in (%s)"
                , StringUtils.convertSet2DBCommaStr(userIds))).findAsync(LUser.class).listen(new FindMultiCallback() {
            @Override
            public void onFinish(List t) {
                if (callback != null) {
                    callback.callback(t);
                }
            }
        });
    }

    public void getUserFromNetwork(final String userId, final OnUserCallback callback) {
        OkRequest.getInstance().withUrl(UrlConfig.QUERY_USER_PHOTO).withRequest(new RUserRequest(
                userId)).doRequest(UserCacheMgr.class.getSimpleName(), new OkCallback<RUserResponse>() {
            @Override
            public void onResponse(RUserResponse rUserResponse, String srcData) {
                if (rUserResponse.isSuccess()) {
                    List<LUser> rUsers = rUserResponse.getrUserList();
                    if (rUsers != null && !rUsers.isEmpty()) {
                        final LUser lUser = rUsers.get(0);
                        if (callback != null) {
                            callback.callback(lUser);
                        }
                        userMap.put(userId, lUser);
                        lUser.saveOrUpdateAsync("userId=?", lUser.getUserId()).listen(new SaveCallback() {
                            @Override
                            public void onFinish(boolean success) {
                                if (success) {
                                    Logger.e("用户信息缓存：" + lUser);
                                }
                            }
                        });
                        return;
                    }
                }
                if (callback != null) {
                    LUser user = new LUser();
                    user.setUserId(userId);
                    callback.callback(user);
                }
            }
        });

    }

    public void getUsersFromNetwork(final OnUsersCallback callback, final String... userIds) {
        String commaStr = StringUtils.convertSet2DBCommaStr(userIds);
        OkRequest.getInstance().withUrl(UrlConfig.QUERY_USER_PHOTO).withRequest(new RUserRequest(
                commaStr)).doRequest(UserCacheMgr.class.getSimpleName(), new OkCallback<RUserResponse>() {
            @Override
            public void onResponse(RUserResponse rUserResponse, String srcData) {
                if (rUserResponse.isSuccess()) {
                    List<LUser> lUsers = new ArrayList<>();
                    for (LUser user : rUserResponse.getrUserList()) {
                        userMap.put(user.getUserId(), user);
                        lUsers.add(user);
                    }
                    if (callback != null) {
                        callback.callback(rUserResponse.getrUserList());
                    }
                    DataSupport.saveAllAsync(lUsers);
                } else {
                    if (callback != null) {
                        callback.callback(new ArrayList<LUser>());
                    }
                }
            }
        });

    }

    public IUser getUser(String userId) {
        IUser user = userMap.get(userId);
        if (user != null) {
            return user;
        } else {
            return DataSupport.where("userId=?", userId).findLast(LUser.class);
        }
    }

    public void getUserAsync(String userId, OnUserCallback callback) {
        LUser user = userMap.get(userId);
        if (user != null) {
            callback.callback(user);
        } else {
            getUserFromDB(userId, callback);
        }
    }

    /**
     * 删除某个用户的缓存信息
     *
     * @param userId
     */
    public void deleteUserCacheByUserId(String userId) {
        userMap.remove(userId);
        DataManager.deleteUserByUserId(userId);
    }

    public void deleteAllUsers() {
        userMap.clear();
        DataSupport.deleteAll(LUser.class);
    }

}
